import {
  find,
  cancel,
  received,
  reminder,
  payment,
  del
} from '../../../api/order';
import {
  submit,
  query
} from '../../../api/payment';
import {
  buyForOrder
} from '../../../api/cart';
import {
  create
} from '../../../api/giftCard.js'
const util = require('../../../utils/util.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: 'https://icweiliimg1.pstatp.com/weili/l/540018848208912837.webp',
    orderForm: null,
    id: '',
    orderLog: '',
    currentTab: 0,
    payments: [],
    left_time: "00:00",
    timeType: false,
    transferType:false,
    giftNum:0,
    shippingEmloyeeList:[],
    extractCodeType:false,
    shopName:'',
    shopPhone:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.data.id = options.id
    this.data.currentTab = options.currentTab
  },
  onShow: function() {
    this.findClick(this.data.id)
  },
  onUnload: function() {
    clearInterval(this.data.timer);
  },
  cancelClick(data) {
    console.log(data)
    var _this = this
    wx.showModal({
      title: '确认取消订单？',
      content: '取消后可在已关闭订单再次购买',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          _this.loadCancel(data.currentTarget.dataset.id)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  receivedClick() {
    var _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认收货！',
      success(res) {
        if (res.confirm) {
          received(_this.data.id).then(
            res => {
              if (res.type == 'success') {
                wx.showToast({
                  title: res.content,
                })
                _this.findClick(_this.data.id)
                // _this.confirmClick()
              }
            }
          ).catch(error => {
            console.log(error)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  logisticsClick() {
    wx.navigateTo({
      url: '/pages/member/logistics/list?id=' + this.data.id,
    })
  },
  confirmClick() {
    wx.navigateTo({
      url: '/pages/member/order/confirm',
    })
  },
  evaluationClick() {
    wx.navigateTo({
      url: '/pages/member/order/evaluation?id=' + this.data.id,
    })
  },
  refundClick() {
    wx.navigateTo({
      url: '/pages/member/order/refund',
    })
  },
  findClick(data) {
    var _this = this
    console.log(data)
    find(data).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.orderForm = res.data.order
          _this.data.orderForm.createDate = util.datetimeFormat(_this.data.orderForm.createDate)
          _this.data.orderForm.estimateDate = util.datetime(_this.data.orderForm.estimateDate)
          if (!util.isNull(res.data.orderLog)) {
            res.data.orderLog.forEach(function(item) {
              item.createDate = util.datetimeFormat(item.createDate)
            })
            _this.data.orderLog = res.data.orderLog
          }
          _this.data.orderForm.itemList.forEach(function (item) {
            item.thumbnail = util.thumbnail(item.thumbnail,170,170)
          })
          res.data.payments.forEach(item=>{
            item.attach=JSON.parse(item.attach)
          })
          _this.data.payments = res.data.payments
          if (res.data.order.paymentStatus == 0) {
            _this.countDown(res.data.order.createDate)
          }
          var subShop = []
          var subPlan = []
          res.data.order.itemList.forEach(function(item){
            if (item.subType == 0){
              subShop.push(item)
            }else if(item.subType == 1){
              subPlan.push(item)
            }
          })
          if(subPlan.length > 0){
            subPlan.forEach(function (item) {
              if (subShop.length > 0){
                _this.data.giftNum += item.quantity + 1
              }else{
                _this.data.giftNum += item.quantity
              }
            })
          }else{
            _this.data.giftNum = 1
          }
          _this.data.shippingEmloyeeList = res.data.shippingEmloyeeList
          _this.data.shopName = res.data.shopName
          _this.data.shopPhone = res.data.telephone
          _this.setData({
            orderForm: _this.data.orderForm,
            orderLog: _this.data.orderLog,
            payments: _this.data.payments,
            giftNum: _this.data.giftNum,
            shippingEmloyeeList:_this.data.shippingEmloyeeList,
            shopName:_this.data.shopName,
            shopPhone:_this.data.shopPhone
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  loadCancel(data) {
    var _this = this
    console.log(data)
    cancel(data).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          wx.showToast({
            title: res.content,
          })
          _this.findClick(_this.data.id)
        }
      }
    ).catch(error => {
      wx.showToast({
              icon: "none",
        title: error.content,
      })
    })
  },
  copyClick() {
    wx.setClipboardData({
      data: this.data.orderForm.sn,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },
  refundsclick() {
    wx: wx.navigateTo({
      url: '/pages/member/order/refund?id=' + this.data.orderForm.id,
    })
  },
  returnDetailsClick() {
    wx.navigateTo({
      url: '/pages/member/order/refund_details?id=' + this.data.orderForm.id,
    })
  },
  clockClick() {
    var _this = this
    reminder(_this.data.id).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          wx.showToast({
            title: res.content,
          })
        }
      }
    ).catch(error => {
      wx.showToast({
              icon: "none",
        title: error.content,
      })
    })
  },
  paymentClick(data) { // 付款
    payment(data.currentTarget.dataset.id).then(res => {
      if (res.type == 'success') {
        console.log(res)
        this.submitClick(res)
      } else {
        wx.showToast({
                icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.showToast({
              icon: "none",
        title: error.content,
      })
    })
  },
  submitClick(data) {
    var _this = this
    _this.data.sn = data.data.sn
    wx.showLoading({
      title: '加载中...',
    })
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function(red) {
            _this.queryClick()
          },
          'fail': function(red) {
            console.log(red);
          }
        })
      } else {
        wx.showToast({
                icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.showToast({
              icon: "none",
        title: error.content,
      })
    })
  },
  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500,
          success: function() {
            setTimeout(function() {
              wx.navigateBack({})
            }, 1500)
          }
        })
      } else {
        wx.navigateBack({})
      }
    }).catch(error => {
      wx.showToast({
              icon: "none",
        title: error.content,
      })
    })
  },
  again() { // 再次购买
    var _this = this
    console.log(this.data.orderForm)
    var product = this.data.orderForm.itemList[0]
    let data = {}
    data.orderId = product.orderId
    data.uuid = app.globalData.uuid
    buyForOrder(data).then(
      res => {
        if (res.type == 'success') {
          wx.navigateTo({
            url: '/pages/goods/submit/index',
          })
        }
      }
    ).catch(error => {
      wx.showToast({
        title: '服务器开小差了，请重新点击购买',
        icon: 'none',
        duration: 2000
      })
    })
  },
  countDown: function(data) {
    var that = this;
    that.data.timer = setInterval(function() {
      var create_time = data.replace(/-/g, "/");
      console.log(create_time)
      //计算剩余时间差值
      var leftTime = (new Date(create_time).getTime() + 30 * 60 * 1000) - (new Date().getTime());
      if (leftTime > 0) {
        //计算剩余的分钟
        var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
        //计算剩余的秒数
        var seconds = parseInt(leftTime / 1000 % 60, 10);
        that.data.left_time = minutes + "分" + seconds + "秒";
        that.data.timeType = false
        that.setData({
          left_time: that.data.left_time,
          timeType: that.data.timeType
        });
      } else {
        //移除超时未支付的订单
        that.data.timeType = true
        that.setData({
          timeType: that.data.timeType
        })
      }
    }, 1000);
  },
  delClick() {
    var _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认删除！',
      success(res) {
        if (res.confirm) {
          del(_this.data.id).then(
            res => {
              if (res.type == 'success') {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          ).catch(error => {
            console.log(error)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  transferClick(){
    this.data.transferType = !this.data.transferType
    this.setData({
      transferType: this.data.transferType
    })
  },
  transferCancel(){
    this.data.transferType = false
    this.setData({
      transferType: this.data.transferType
    })
  },
  saveTransferClick(){
    var _this = this
    create({
      orderId: _this.data.id
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.showToast({
          title: '创建成功',
        })
        _this.findClick(_this.data.id)
        wx.navigateTo({
          url: '/pages/member/giftCard/giftCard',
        })
        this.data.transferType = false
        this.setData({
          transferType: this.data.transferType
        })
      }
    }).catch(error => {
      wx.showToast({
              icon: "none",
        title: error.content,
      })
    })
  },
  phoneClick(data){
    console.log(data)
    wx.showModal({
      title: '提示',
      content: '是否确认联系骑手',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          if (data.currentTarget.dataset.mobile) {
            wx.makePhoneCall({
                    phoneNumber: data.currentTarget.dataset.mobile // 仅为示例，并非真实的电话号码
            })
          }else{
            wx.showToast({
                    icon: "none",
              title: '暂无联系方式',
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  extractCodeClick(data){
    console.log(data)
    var _this = this
    this.data.extractCodeType = !this.data.extractCodeType
    this.setData({
      extractCodeType:this.data.extractCodeType
    })
    var id = data.currentTarget.dataset.id
    _this.selectComponent("#extract").qrcodeClick(id);
  },
  qrcodeCancelClick(){
    this.data.extractCodeType = !this.data.extractCodeType
    this.setData({
      extractCodeType:this.data.extractCodeType
    })
  },
  toCall() {
    let _this = this
    console.info()
          if (_this.data.shopPhone) {
      wx.makePhoneCall({
              phoneNumber: _this.data.shopPhone // 仅为示例，并非真实的电话号码
      })
    }
  },
})